package com.zprmb.udzt;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zprmb.udzt.activity.V6LoginActivity4;
import com.zprmb.udzt.alert.AlertView;
import com.zprmb.udzt.alert.OnDismissListener;
import com.zprmb.udzt.alert.OnItemClickListener;
import com.zprmb.udzt.gesture.GestureVerifyActivity;
import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.model.Yijuhua;
import com.zprmb.udzt.util.BitmapUtils;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.FingerprintUtil;
import com.zprmb.udzt.util.MySharePreferenceUtil;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.view.RoundImageView;

import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class V6_Finger_CheckActivity extends GeActivity implements OnItemClickListener, OnDismissListener {
    //    private ImageView img_finger_bg;
    private TelephonyManager tm;
    private SharedPreferences sha;
    private CustomDialog_view_new.Builder builder;
    private AlertView mAlertView;
    private TextView text_login;
    private RoundImageView user_logo;
    private TextView text_welcome;

    TextView text_yue;
    TextView text_xiexian;
    TextView text_ri;
    SpannableString msp = null;
    TextView text_yu;
    TextView text_yijuhua;

    //dialog弹框
    ImageView img_showdialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.v6_finger_check);
        BbtApplication.getInstance().addActvity(this);
        sha = getSharedPreferences("config", MODE_PRIVATE);
        tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
//        img_finger_bg = (ImageView) findViewById(img_finger_bg);
//        img_finger_bg.setImageBitmap(BitmapUtils.readBitMap(this, R.mipmap.zhiwenback));
//        Toast.makeText(this, "测试", Toast.LENGTH_SHORT).show();
        text_login = (TextView) findViewById(R.id.text_login);
        text_yue = (TextView) findViewById(R.id.text_yue);
        text_xiexian = (TextView) findViewById(R.id.text_xiexian);
        text_ri = (TextView) findViewById(R.id.text_ri);
        text_yu = (TextView) findViewById(R.id.text_yu);
        text_welcome = (TextView) findViewById(R.id.text_welcome);
        text_yijuhua = (TextView) findViewById(R.id.text_yijuhua);
        img_showdialog = (ImageView) findViewById(R.id.img_showdialog);
        img_showdialog.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onFingerprintClick(null);
            }
        });
  /*      if (sha.getString("userNameText", "").equals("") || sha.getString("userNameText", "").equals("null")) {
            text_welcome.setText(sha.getString("mobile", "").substring(0, 3) + "****" + sha.getString("mobile", "").substring(7, sha.getString("mobile", "").length()));
        } else {
            text_welcome.setText("欢迎您， " + sha.getString("userNameText", ""));
        }*/


        Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/DIN-RegularAlternate.otf");


//        Typeface font2 =typeFace.create(Typeface.SANS_SERIF, Typeface.BOLD);
        text_ri.setTypeface(typeFace);

        text_ri.getPaint().setFakeBoldText(true);


        text_yue.setTypeface(typeFace);
        text_yu.setTypeface(typeFace);
        Paint mp2 = new Paint();

        Typeface typeFace2 = Typeface.createFromAsset(getAssets(), "fonts/fangsong.ttf");


        mp2.setTypeface(typeFace2);
//        text_xiexian.setTypeface(typeFace2);
        text_xiexian.setRotation(2);

        text_xiexian.setTypeface(typeFace2);
//        text_xiexian.getPaint().setFakeBoldText(true);

//        text_xiexian.setRotation(12);

        Calendar c = Calendar.getInstance();//

        int mYear = c.get(Calendar.YEAR); // 获取当前年份
        int mMonth = c.get(Calendar.MONTH) + 1;// 获取当前月份
        int mDay = c.get(Calendar.DAY_OF_MONTH);// 获取当日期

        if (isFinger()) {
            onFingerprintClick(null);
        }

        user_logo = (RoundImageView) findViewById(R.id.user_logo);
    /*    if (sha.getString("photoUrl", "").equals("") || sha.getString("photoUrl", "").equals("null")) {
            if (getSex().equals("女")) {
                user_logo.setImageBitmap(BitmapUtils.readBitMap(V6_Finger_CheckActivity.this, R.drawable.img_girl));
            } else {
                user_logo.setImageBitmap(BitmapUtils.readBitMap(V6_Finger_CheckActivity.this, R.drawable.img_boy));
            }


        } else {
//			BbtApplication.getInstance().imageLoader.loadImageSync(sha.getString("photoUrl", ""),BbtApplication.getInstance().displayImageOptions(R.drawable.img_girl);
            if (sha.getString("fileicon", "").equals("")) {
//                Picasso.with(V6_Finger_CheckActivity.this).load(sha.getString("photoUrl", "")).error(R.drawable.img_girl).into(user_logo);
            } else {
//                user_logo.setImageBitmap(getSdBitmap(sha.getString("fileicon", "")));
            }
//            handler.sendMessage(message);
//						getBitmap(sha.getString("photoUrl", ""));
//			BbtApplication.getInstance().display(), user_logo);
        }*/
        String token = (String) MySharePreferenceUtil.get(V6_Finger_CheckActivity.this, "mytoken", "");


        try {
            token = URLEncoder.encode(token, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String sex = (String) MySharePreferenceUtil.get(V6_Finger_CheckActivity.this, "sex", "");
        String userName = (String) MySharePreferenceUtil.get(V6_Finger_CheckActivity.this, "userNameText", "");
        final String userMobile = (String) MySharePreferenceUtil.get(V6_Finger_CheckActivity.this, "userMobile", "");

        String welcomeName = (String) MySharePreferenceUtil.get(V6_Finger_CheckActivity.this, "welcomeName", "");
        if (sex.equals("男")) {
            user_logo.setImageBitmap(BitmapUtils.readBitMap(V6_Finger_CheckActivity.this, R.drawable.img_boy));
        } else if (sex.equals("女")) {
            user_logo.setImageBitmap(BitmapUtils.readBitMap(V6_Finger_CheckActivity.this, R.drawable.img_girl));
        } else {
            user_logo.setImageBitmap(BitmapUtils.readBitMap(V6_Finger_CheckActivity.this, R.drawable.img_boy));
        }
        if (userName.equals("") || userName.equals("null")) {
//                        text_welcome.setText(sha.getString("mobile", "").substring(0, 3) + "****" + sha.getString("mobile", "").substring(7, sha.getString("mobile", "").length()));
            text_welcome.setText(userMobile.substring(0, 3) + "****" + userMobile.substring(7, userMobile.length()));
        } else {
            text_welcome.setText("欢迎您， " + welcomeName);
        }


        text_login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
               /* Intent intent = new Intent(V6_Finger_CheckActivity.this, V6LoginActivity.class);
                startActivity(intent);
                finish();*/
                Intent intent2 = new Intent(V6_Finger_CheckActivity.this, V6LoginActivity.class);
                intent2.putExtra("close", 1);
                Editor editor2 = sha.edit();
                editor2.putString("token", "");
                editor2.putString("token", "");
                editor2.putString("mobile", userMobile);


                editor2.commit();
                startActivity(intent2);

                V6_Finger_CheckActivity.this.finish();

            }
        });

      /*  VolleryUtil3 volleryUtil = new VolleryUtil3() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                Log.d(jsonObject.toString(), "3333333333333333");

                // TODO Auto-generated method stub
                if (jsonObject.optInt("success") == 1) {
                    LogUtils.e(V6_Finger_CheckActivity.this, "个人信息" + jsonObject.toString());
                    JSONObject json1 = jsonObject.optJSONObject("data");

                    JSONObject json = jsonObject.optJSONObject("data");
                    String sex = json.optString("sex");
//                    userNameText=张宇
                    String userName = json.optString("userNameText");
                    MySharePreferenceUtil.put(V6_Finger_CheckActivity.this, "userNameText", userName);
//                    userMobile=13674610754
                    String userMobile = json.optString("userMobile");
                    String welcomeName = json.optString("welcomeName");
//                    welcomeName=张先生

                    if (sex.equals("男")) {
                        user_logo.setImageBitmap(BitmapUtils.readBitMap(V6_Finger_CheckActivity.this, R.drawable.img_boy));
                    } else if (sex.equals("女")) {
                        user_logo.setImageBitmap(BitmapUtils.readBitMap(V6_Finger_CheckActivity.this, R.drawable.img_girl));
                    } else {
                        user_logo.setImageBitmap(BitmapUtils.readBitMap(V6_Finger_CheckActivity.this, R.drawable.img_boy));
                    }
                    if (userName.equals("") || userName.equals("null")) {
//                        text_welcome.setText(sha.getString("mobile", "").substring(0, 3) + "****" + sha.getString("mobile", "").substring(7, sha.getString("mobile", "").length()));
                        text_welcome.setText(userMobile.substring(0, 3) + "****" + userMobile.substring(7, userMobile.length()));
                    } else {
                        text_welcome.setText("欢迎您， " + welcomeName);
                    }
//						Editor ed=sha.edit();
//						ed.putInt("islogin", 1);
//						ed.commit();
//					}
                } else {
                    if (jsonObject.optString("comment").equals("please login")) {
//						Editor ed=sha.edit();
//						ed.putInt("islogin", 0);
//						ed.commit();
                        Log.e("login", jsonObject.toString());
//                        startActivity(new Intent(V6_Finger_CheckActivity.this, V6LoginActivity.class));


                    } else {
                        Toast.makeText(V6_Finger_CheckActivity.this, jsonObject.optString("comment"), 2000).show();
                    }
                }

            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };


        volleryUtil.setHeaders("token", token);
        volleryUtil.setRequestMethod(0);
        volleryUtil.execute(V6_Finger_CheckActivity.this, Constant.URL + "/api/v5/user/accountCenter", "");*/
        AjaxParams params = new AjaxParams();
        VolleryUtil vollery = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                Log.e("ssssg", jsonObject.toString());
                JSONObject json1 = jsonObject.optJSONObject("data");
                if (jsonObject.optInt("success") == 1) {

                    Gson gson = new Gson();
                    Yijuhua yijuhua = new Yijuhua();
                    yijuhua = gson.fromJson(jsonObject.toString(), Yijuhua.class);
                    text_yijuhua.setText(yijuhua.getData().getAdsTitle());

//                    text_ri.setText(mDay + "");
//                    text_yue.setText(mMonth + "");
                    /**/
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-M-dd");
                    Long time = new Long(yijuhua.getData().getTime());


                    String d = format.format(time);
                    Log.d(d, "333333333333333");

                    SimpleDateFormat format_day = new SimpleDateFormat("dd");

                    String day = format.format(time);
                    Log.d(day, "9999999999999");
                    Calendar cld = Calendar.getInstance();
                    try {
                        Date date = format.parse(d);
                        cld.setTime(date);
                        Log.d("年份：", String.valueOf(cld.get(Calendar.YEAR)));
                        Log.d("月份：", String.valueOf(+(cld.get(Calendar.MONTH) + 1)));
                        Log.d("日：", String.valueOf(+(cld.get(Calendar.DAY_OF_MONTH))));
                        text_ri.setText(cld.get(Calendar.DAY_OF_MONTH) + "");
                        text_yue.setText(cld.get(Calendar.MONTH) + 1 + "");

                  /*      System.out.println("年份："+cld.get(Calendar.YEAR));
                        System.out.println("月份："+(cld.get(Calendar.MONTH)+1));
                        System.out.println("日："+cld.get(Calendar.DAY_OF_MONTH));*/
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }


            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };

        vollery.setRequestMethod(0);
        vollery.setShow(true);
        vollery.execute(this, Constant.URL + "/api/v7/getAppCalendar",
                params.toString());

    }

    private long mLastBackTime = 0;
    private long TIME_DIFF = 2 * 1000;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long now = new Date().getTime();
            if (now - mLastBackTime < TIME_DIFF) {

                BbtApplication.getInstance().exit();
                android.os.Process.killProcess(android.os.Process.myPid());
                //BbtApplication.getInstance().exit();

                finish();
                return super.onKeyDown(keyCode, event);
            } else {
                mLastBackTime = now;
                Toast.makeText(this, "再按一次退出优点智投", 2000).show();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private Bitmap getSdBitmap(String path) {
        File mFile = new File(path);
        Bitmap bitmap;
        //若该文件存在T
        if (mFile.exists()) {
//	        	LogUtils.e(GestureVerifyActivity.this.this, "sd卡图片存在");
            bitmap = BitmapFactory.decodeFile(path);
            return bitmap;
        } else {
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img_girl);
        }
        return bitmap;
    }

    public void onFingerprintClick(View v) {

        FingerprintUtil.callFingerPrint(new FingerprintUtil.OnCallBackListenr() {

            @Override
            public void onSupportFailed() {
                showToast("当前设备不支持指纹");
            }

            @Override
            public void onInsecurity() {
                showToast("当前设备未处于安全保护中");
            }

            @Override
            public void onEnrollFailed() {
                showToast("请到设置中设置指纹");
            }

            @Override
            public void onAuthenticationStart() {

                builder = new CustomDialog_view_new.Builder(V6_Finger_CheckActivity.this);
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        FingerprintUtil.cancel();
                        builder.create().dismiss();
                    }
                });
                builder.setMessage("请验证已有手机指纹");
                builder.setMessage2("");
                builder.create().setCancelable(false);
                builder.create().show();
            }

            @Override
            public void onAuthenticationError(int errMsgId, CharSequence errString) {
                showToast(errString.toString());
//                Log.e("dialog", builder.create()+"");
                if (builder.create() != null) {
                    builder.create().mdissmis();
                }
            }

            @Override
            public void onAuthenticationFailed() {
                showToast("解锁失败");
            }

            @Override
            public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
//                showToast(helpString.toString());
            }

            @Override
            public void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) {
                showToast("解锁成功");
                Log.e("dialog", builder.create() + "");
//                Log.e("object", builder.create()+""+builder.create().isShowing()+"");
                if (builder.create() != null) {
                    builder.create().mdissmis();
                    upData("FINGERPRINT");
                }
                MySharePreferenceUtil.put(V6_Finger_CheckActivity.this, "newintentflag", "1");
                upData("FINGERPRINT");
            }
        });
    }

    private void upData(String type) {
        if (!network()) {
            finish();
        }
        MySharePreferenceUtil.put(V6_Finger_CheckActivity.this, "newintentflag", "1");
        AjaxParams params = new AjaxParams();
        params.put("loginName", sha.getString("mobile", ""));
        params.put("loginType", type);
        params.put("appVersion", getAppVersion());
        try {
            params.put("cipher", URLEncoder.encode(sha.getString("password", ""), "UTF-8"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        VolleryUtil vollery = new VolleryUtil() {


            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub

                Log.e("ssssg", jsonObject.toString());
                JSONObject json1 = jsonObject.optJSONObject("data");
                if (jsonObject.optInt("success") == 1) {
                    MySharePreferenceUtil.remove(V6_Finger_CheckActivity.this, "mytoken");
                    Editor editor = sha.edit();
                    editor.putString(
                            "token",
                            json1.optString(
                                    "token"));
                    editor.putString(
                            "userId",
                            json1.optString(
                                    "userId"));
                    editor.putString(
                            "photoUrl",
                            json1.optString(
                                    "photoUrl"));
                    editor.putString(
                            "mobile",
                            json1.optString(
                                    "mobile"));
                    editor.putString(
                            "usercode",
                            json1.optString(
                                    "userCode"));
                    editor.putString("loginName", getIntent().getStringExtra("phone"));
                    editor.putInt("islogin", 1);
                    editor.commit();


                    MySharePreferenceUtil.put(V6_Finger_CheckActivity.this, "mytoken", json1.optString(
                            "token"));
                    int close = getIntent().getIntExtra("close", 0);
                    if (close == 1) {

                        if (!json1.optString("accountToReveal").equals("")) {
                            mAlertView = new AlertView("", json1.optString("accountToReveal"), null, new String[]{"确定"}, null, V6_Finger_CheckActivity.this, AlertView.Style.Alert, V6_Finger_CheckActivity.this);
                            mAlertView.show();

                            return;
                        }

                        if (getIntent().getIntExtra("web", 0) == 1) {
                            if (getIntent().getIntExtra("assets", 0) == 1) {

                                Intent intent = new Intent();


//							intent.putExtra("resultcode", 1);
                                intent.putExtra("accountToReveal", json1.optString("accountToReveal"));

                                setResult(2, intent);
                                finish();
                                return;
                            }
                            Intent intent = new Intent();
                            intent.putExtra("resultcode", 1);
                            intent.putExtra("accountToReveal", json1.optString("accountToReveal"));
                            setResult(1, intent);
                            Log.e("web", "web");
                            finish();

                        } else {

                            Intent intent = new Intent();
                            intent.putExtra("accountToReveal", json1.optString("accountToReveal"));
                            setResult(1, intent);
                            V6_Finger_CheckActivity.this.finish();
                        }
                        return;

                    }
                    Intent intent = new Intent(V6_Finger_CheckActivity.this, MainActivity.class);
                    MySharePreferenceUtil.put(V6_Finger_CheckActivity.this, "newintentflag", "1");
                    startActivity(intent);


                    V6_Finger_CheckActivity.this.finish();


                } else if (jsonObject.optInt("success") == 0) {
                    int close = getIntent().getIntExtra("close", 0);
                    if (close == 1) {

                        if (!json1.optString("accountToReveal").equals("")) {
                            mAlertView = new AlertView("", json1.optString("accountToReveal"), null, new String[]{"确定"}, null, V6_Finger_CheckActivity.this, AlertView.Style.Alert, V6_Finger_CheckActivity.this);
                            mAlertView.show();

                            return;
                        }

                        if (getIntent().getIntExtra("web", 0) == 1) {
                            if (getIntent().getIntExtra("assets", 0) == 1) {


                                Intent intent = new Intent();


//							intent.putExtra("resultcode", 1);
                                intent.putExtra("accountToReveal", json1.optString("accountToReveal"));

                                setResult(2, intent);
                                finish();
                                return;
                            }
                            Intent intent = new Intent();
                            intent.putExtra("resultcode", 1);
                            intent.putExtra("accountToReveal", json1.optString("accountToReveal"));
                            setResult(1, intent);
                            Log.e("web", "web");
                            finish();

                        } else {

                            Intent intent = new Intent();
                            intent.putExtra("accountToReveal", json1.optString("accountToReveal"));
                            setResult(1, intent);
                            V6_Finger_CheckActivity.this.finish();
                        }
                        return;

                    }
                } else {


                    if (jsonObject.optString("comment").equals("please login")) {
                        Intent intent = new Intent(V6_Finger_CheckActivity.this, V6LoginActivity.class);
                        startActivity(intent);
                    }
                    V6_Finger_CheckActivity.this.finish();

                }

            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub
                V6_Finger_CheckActivity.this.finish();
            }
        };

        String token = (String) MySharePreferenceUtil.get(V6_Finger_CheckActivity.this, "mytoken", "");


        try {
            token = URLEncoder.encode(token, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        vollery.setHeaders("appVersion", getAppVersion());
        vollery.setHeaders("token", token);

        vollery.setHeaders("client", "android");
        vollery.setHeaders("deviceToken", getdevice_token());
        vollery.setHeaders("deviceId", tm.getDeviceId());
        vollery.setHeaders("mobileType", getDeviceType());
        vollery.setRequestMethod(1);
        vollery.setShow(true);
        vollery.execute(this, Constant.URL + "/api/v6/login/app?",
                params.toString());
    }

    @Override
    public void onDismiss(Object o) {
    }

    @Override
    public void onItemClick(Object o, int position) {
        Editor editor = sha.edit();

        Intent intent = new Intent(V6_Finger_CheckActivity.this, V6LoginActivity4.class);
        editor.putString(sha.getString("mobile", "123456"), "");
        editor.putString("token", "");
        editor.commit();
        intent.putExtra("close", 1);
        startActivity(intent);
        V6_Finger_CheckActivity.this.finish();
        finish();
    }
}
